package com.pospi.xstore.ui.login_ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dialog.WaitingDialog;
import com.pospi.xstore.dto.GiveBeen;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.MenuDto;
import com.pospi.xstore.dto.ProGoodsBeen;
import com.pospi.xstore.dto.Promotionbeen;
import com.pospi.xstore.dto.ReduceProBeen;
import com.pospi.xstore.dto.ReturnDto;
import com.pospi.xstore.dto.SingleProBeen;
import com.pospi.xstore.dto.Tablebeen;
import com.pospi.xstore.greendao.DaoSession;
import com.pospi.xstore.greendao.GiveBeenDao;
import com.pospi.xstore.greendao.ProGoodsBeenDao;
import com.pospi.xstore.greendao.PromotionbeenDao;
import com.pospi.xstore.greendao.ReduceProBeenDao;
import com.pospi.xstore.greendao.SingleProBeenDao;
import com.pospi.xstore.greendao.TablebeenDao;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.MainActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveMenuInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @Bind(R.id.user_name)
    EditText userName;
    @Bind(R.id.et_pwd)
    EditText etPwd;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.user_count)
    EditText user_count;

    private Dialog dialog;
    private String token;
    private TablebeenDao tablebeenDao;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeloding();
                    Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                    downMenu();
                    break;
                case 2:
                    closeloding();
                    Toast.makeText(LoginActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    closeloding();
                    downGoods();
                    break;
                case 4:
                    closeloding();
                    Toast.makeText(LoginActivity.this, "下载商品完成", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(LoginActivity.this, SelectStoreActivity.class));
                    SPHelper.getInstance().putBoolean("isLogin", true);
                    SPHelper.getInstance().putString(Constant.COUNT_NAME,userName.getText().toString().trim());
                    SPHelper.getInstance().putString(Constant.COUNT_QYH,user_count.getText().toString().trim());
                    finish();
                    break;
                case 5:
                    closeloding();
                    Toast.makeText(LoginActivity.this, "服务器异常，请重试", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };
    private String logid;
    private String id;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        rePermition();


    }



    //下载分类
    private void downMenu() {
        final List<MenuDto> menuDtos = new ArrayList<>();
//        showlodindDialog("正在下载商品分类");
        RequestParams params = new RequestParams();
        params.put("logid", logid);
        params.put("sysid", id);
        params.put("model", "base.mbase");
        params.put("table", "base_goodscat");
        params.put("fun", "find");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    for (int j=0;j<result.length();j++) {
                        MenuDto menuDto = new MenuDto();
                        menuDto.setSid(result.getJSONObject(j).getString("id"));
                        menuDto.setName(result.getJSONObject(j).getString("name"));
                        menuDtos.add(menuDto);
                    }
                    SaveMenuInfo.saveAsJson(getApplication(), menuDtos);//存储分类
                    Log.i("login", "分类存储成功");
                    Message message = Message.obtain();
                    message.what = 3;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 3;
                handler.sendMessage(message);
            }
        });

    }
    //下载商品
    private void downGoods() {
        showlodindDialog("正在下载商品");
        RequestParams params = new RequestParams();
        params.put("logid", logid);
        params.put("sysid", id);
        params.put("model", "base.mgoodsbase");
        params.put("table", "base_goodsbase");
        params.put("fun", "find");
        params.put("page", "");
        params.put("limit", "");

        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, final byte[] bytes) {
                Log.i("login", new String(bytes));
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        saveGoods(new String(bytes));
                    }
                }).start();


            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }


    private GoodsDao goodsDao;
    private void saveGoods(String response) {
        goodsDao = new GoodsDao(getApplicationContext());
        final List<GoodsDto> dtos = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(response);
            JSONArray goodsJson = object.getJSONArray("result");
            for (int i = 0;i<goodsJson.length();i++) {
                GoodsDto dto = new GoodsDto();
                JSONObject data = goodsJson.getJSONObject(i);
                dto.setSid(data.getString("id"));//商品id
                dto.setName(data.getString("name"));//商品名
                dto.setPrice(Double.parseDouble(data.getString("lsj")));//零售价
                dto.setCode(data.getString("barcode"));//商品条码
                dto.setCategory_sid(data.getString("catid"));//分类
                dto.setUnit(data.getString("unit"));//单位
                dto.setSpec(data.getString("spec"));
                dto.setDzc(data.getString("dzc"));
                dtos.add(dto);
            }
            goodsDao.addGoods(dtos);//存储商品
            Log.i("login", "商品存储成功");
            Message message = Message.obtain();
            message.what = 4;
            handler.sendMessage(message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.btn_login)
    public void onClick() {
        if (userName.getText().toString().isEmpty()||user_count.getText().toString().trim().isEmpty()) {
            Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
        } else if (etPwd.getText().toString().isEmpty()) {
            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
        } else {
            showlodindDialog("正在登陆");
            RequestParams params = new RequestParams();
            params.put("fun", "login");
            params.put("model", "system.mlogin");
            params.put("logid","0");
            final JSONObject object = new JSONObject();
            try {
                object.put("code", user_count.getText().toString().trim());
                object.put("gh", userName.getText().toString().trim());
                object.put("pwd", etPwd.getText().toString().trim());
                object.put("logtype", "app");
                object.put("clientid", getSN());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            params.put("pds", object.toString());
//            params.put("Imei", getPhoneMac());
            Log.i("login", params.toString());

            LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    Log.i("login", new String(bytes));
                    try {
                        JSONObject jsonObject = new JSONObject(new String(bytes));
                        String flag = jsonObject.getString("flag");
                        if (flag.equals("1")) {
                            JSONObject resultObject = jsonObject.getJSONObject("result");
                            JSONObject object1 = resultObject.getJSONObject("user");
                            JSONObject object2 = resultObject.getJSONObject("sys");
                            JSONObject object = resultObject.getJSONObject("customer");
                            logid = object1.getString("logid");
                            id = object2.getString("id");
                            SPHelper.getInstance().putString(Constant.CUSTOMER, object1.getString("id"));
                            SPHelper.getInstance().putString(Constant.CUSTOMER_name, object1.getString("cname"));
                            SPHelper.getInstance().putString(Constant.USER_ID, logid);
                            SPHelper.getInstance().putString(Constant.SYS_ID, id);
                            Message message = Message.obtain();
                            message.what = 1;
                            handler.sendMessage(message);
                        } else {
                            Message message = Message.obtain();
                            message.what = 2;
                            message.obj = jsonObject.getString("errMsg");
                            handler.sendMessage(message);
                        }
                        Log.i("login", jsonObject.getString("errMsg"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    Message message = Message.obtain();
                    message.what = 5;
                    handler.sendMessage(message);
                }
            });
        }
    }



    public void showDialog(String msg) {
        if (dialog == null) {
            dialog = WaitingDialog.createLoadingDialog(LoginActivity.this, msg);
            dialog.show();
        }
    }
    private String getSN() {
        String sn = "";
        try {
            Class c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            Log.i("sunmi", "the sn:" + (String) get.invoke(c, "ro.serialno"));
            sn = (String) get.invoke(c, "ro.serialno");
//            Log.i("sunmi", "First four characters:"
//                    + (String) get.invoke(c, "ro.serialno").substring(0, 4));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sn;
    }
    public void closeDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }
    private DialogFragment dialogFragment;
    private void showlodindDialog(String msg){
        dialogFragment = new CircleDialog.Builder()
                .setProgressText(msg+"...")
                .setProgressStyle(ProgressParams.STYLE_SPINNER)
                .setCancelable(false)
                .show(getSupportFragmentManager());
    }
    private void closeloding(){
        dialogFragment.dismiss();
    }
    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;
    private void rePermition(){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
    }
}
